package com.example.denglu.servlet;

import com.alibaba.fastjson.JSONObject;
import com.example.denglu.service.UserService;
import com.example.denglu.util.SessionManager;
import com.example.denglu.util.WeChatUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/wechatCallback")
public class WeChatCallbackServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        // 处理微信服务器的验证请求
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        
        // 验证签名
        if (WeChatUtil.checkSignature(signature, timestamp, nonce)) {
            response.getWriter().write(echostr);
        } else {
            response.getWriter().write("error");
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        try {
            // 读取XML消息
            InputStream inputStream = request.getInputStream();
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            Element root = document.getRootElement();
            
            // 获取消息类型
            String msgType = root.elementText("MsgType");
            String openid = root.elementText("FromUserName");
            String toUserName = root.elementText("ToUserName");
            
            // 初始化响应内容
            String responseContent = "欢迎关注";
            String sceneStr = null;
            
            // 从数据库或缓存中获取该用户最近的场景值
            sceneStr = SessionManager.getSceneStrByOpenid(openid);
            System.out.println("当前用户openid: " + openid + ", sceneStr: " + sceneStr);
            
            if ("event".equals(msgType)) {
                String event = root.elementText("Event");
                String eventKey = root.elementText("EventKey");
                
                if ("SCAN".equals(event) || "subscribe".equals(event)) {
                    sceneStr = "subscribe".equals(event) ? 
                              eventKey.replace("qrscene_", "") : eventKey;
                    
                    // 保存场景值和openid的对应关系
                    SessionManager.saveSceneStrForOpenid(openid, sceneStr);
                    
                    // 获取用户信息
                    JSONObject userInfo = WeChatUtil.getUserInfo(openid);
                    
                    // 检查用户是否已绑定手机号
                    boolean hasPhone = UserService.checkUserHasPhone(openid);
                    
                    if (hasPhone) {
                        // 已绑定手机号，检查是否设置了密码
                        boolean needSetPassword = UserService.needSetPassword(openid);
                        if (needSetPassword) {
                            // 需要设置密码
                            SessionManager.setAttribute(sceneStr, "wechat_scanned", true);
                            SessionManager.setAttribute(sceneStr, "wechat_openid", openid);
                            SessionManager.setAttribute(sceneStr, "need_set_password", true);
                            responseContent = "请返回网页继续设置密码";
                        } else {
                            // 已设置密码，可以直接登录
                            SessionManager.setAttribute(sceneStr, "wechat_scanned", true);
                            SessionManager.setAttribute(sceneStr, "wechat_openid", openid);
                            responseContent = "登录成功，请返回网页继续操作";
                        }
                    } else {
                        // 未绑定手机号，保存扫码状态并要求用户发送手机号
                        SessionManager.setAttribute(sceneStr, "wechat_scanned", true);
                        SessionManager.setAttribute(sceneStr, "wechat_openid", openid);
                        SessionManager.setAttribute(sceneStr, "need_phone", true);
                        responseContent = "请发送您的手机号进行账号绑定";
                    }
                }
            } else if ("text".equals(msgType)) {
                // 处理文本消息，可能是手机号
                String content = root.elementText("Content");
                if (content != null && content.matches("^1[3-9]\\d{9}$")) {
                    String phone = content;
                    System.out.println("收到手机号：" + phone + ", sceneStr: " + sceneStr);
                    
                    if (sceneStr != null) {
                        // 获取用户信息
                        JSONObject userInfo = WeChatUtil.getUserInfo(openid);
                        
                        // 创建或更新用户信息，包含手机号
                        boolean success = UserService.createOrUpdateWeChatUser(
                            openid,
                            userInfo.getString("nickname"),
                            userInfo.getString("headimgurl"),
                            phone
                        );
                        
                        if (success) {
                            // 标记需要设置密码
                            SessionManager.setAttribute(sceneStr, "wechat_scanned", true);
                            SessionManager.setAttribute(sceneStr, "wechat_openid", openid);
                            SessionManager.setAttribute(sceneStr, "need_set_password", true);
                            SessionManager.removeAttribute(sceneStr, "need_phone");
                            responseContent = "手机号绑定成功，请返回网页设置密码";
                        } else {
                            responseContent = "手机号绑定失败，请重试";
                        }
                    } else {
                        responseContent = "请先扫描二维码进行登录";
                    }
                } else {
                    responseContent = "请发送正确的手机号码";
                }
            }
            
            // 返回消息给微信服务器
            String responseMsg = String.format(
                "<xml>" +
                "<ToUserName><![CDATA[%s]]></ToUserName>" +
                "<FromUserName><![CDATA[%s]]></FromUserName>" +
                "<CreateTime>%d</CreateTime>" +
                "<MsgType><![CDATA[text]]></MsgType>" +
                "<Content><![CDATA[%s]]></Content>" +
                "</xml>",
                openid, toUserName, System.currentTimeMillis() / 1000, responseContent
            );
            
            response.setContentType("application/xml;charset=UTF-8");
            response.getWriter().write(responseMsg);
            
        } catch (Exception e) {
            System.out.println("处理微信回调异常：" + e.getMessage());
            e.printStackTrace();
            response.getWriter().write("");
        }
    }
} 